var User = {};

// ChagePass
User.PasswordForm = function(frmId, url, params) {
	var form = new Ext.FormPanel({
    closable:true,
    id : frmId,
    url:url,
    frame:true,
    title: Resource["user.chagepassword"],
    bodyStyle:'padding:5px 5px 0',
    
    items: [{
        xtype:'fieldset',
        checkboxToggle:false,
        title: Resource["user.chagepassword"],
        autoHeight:true,
        defaults: {width: 300},
        labelWidth: 120,
        defaultType: 'textfield',
        collapsed: false,
        items :[
        	{
                fieldLabel: Resource["user.currentpassword"],
                name: 'oldPassword',
                inputType : 'password',
                allowBlank:false
            },{
                fieldLabel: Resource["user.newpassword"],
                name: 'password',
                allowBlank : false,
                inputType : 'password'
            },{
            	xtype : 'hidden',
            	name : 'id'
            }, {
            	xtype : 'hidden',
            	name : 'crudaction',
            	value : 'insert-update'
            },{
            	xtype : 'hidden',
            	name : 'page',
            	value : 'password'
            }
        ]
    }],

    tbar: new Ext.Toolbar([{
        text: Resource["common.btsave"],
        iconCls:'x-button-save',
        handler: function(){
        if(form.getForm().isValid()){
            form.getForm().submit({
                url: url,
                waitMsg: Resource["common.msgwaiting"],
                success: function(usergroupForm, o){
                    Ext.MessageBox.show({
				           title: Resource["common.alert"],
				           msg: o.result.messageResponse,
				           buttons: Ext.MessageBox.OK
				       });
                }
            });
        }
    }
        
    },{
        text: Resource["common.btreset"],
        iconCls:'x-button-reset',
        handler: function(){
            form.getForm().reset();
        }
    },{
        text: Resource["common.btclose"],
        iconCls:'x-button-close',
        handler: function(){
            Ext.getCmp('maintabs-id').remove(frmId, true);
        }
    }])
});
	return form;
}
// Profile
User.ProfileForm = function(frmId, url, params) {
	var form = new Ext.FormPanel({
    closable:true,
    id : frmId,
    url:url,
    frame:true,
    title: Resource["user.accountinfo"],
    bodyStyle:'padding:5px 5px 0',
    
    items: [{
        xtype:'fieldset',
        checkboxToggle:false,
        title: Resource["user.accountinfo"],
        autoHeight:true,
        defaults: {width: 300},
        labelWidth: 120,
        defaultType: 'textfield',
        collapsed: false,
        items :[
        	{
                fieldLabel: Resource["user.fullname"],
                name: 'fullname',
                allowBlank:false
            },{
                fieldLabel: Resource["user.email"],
                name: 'email',
                allowBlank : false,
                vtype : 'email'
            },{
                fieldLabel: Resource["user.address"],
                name: 'address',
                allowBlank : false
            },{
            	xtype : 'hidden',
            	name : 'id'
            }, {
            	xtype : 'hidden',
            	name : 'crudaction',
            	value : 'insert-update'
            },{
            	xtype : 'hidden',
            	name : 'page',
            	value : 'profile'
            }
        ]
    }],

    tbar: new Ext.Toolbar([{
        text: Resource["common.btsave"],
        iconCls:'x-button-save',
        handler: function(){
        if(form.getForm().isValid()){
            form.getForm().submit({
                url: url,
                waitMsg: Resource["common.msgwaiting"],
                success: function(usergroupForm, o){
                    Ext.MessageBox.show({
				           title: Resource["common.alert"],
				           msg: o.result.messageResponse,
				           buttons: Ext.MessageBox.OK
				       });
                }
            });
        }
    }
        
    },{
        text: Resource["common.btreset"],
        iconCls:'x-button-reset',
        handler: function(){
    		User.UpdateLoad();
        }
    },{
        text: Resource["user.chagepassword"],
        iconCls:'x-button-edit',
        handler: function(){
    		showPasswordForm();
        }
    },{
        text: Resource["common.btclose"],
        iconCls:'x-button-close',
        handler: function(){
            Ext.getCmp('maintabs-id').remove(frmId, true);
        }
    }])
});
	User.UpdateLoad = function(){
		form.getForm().load({
			url : url,
			params : params,
			waitMsg:Resource["common.msgwaiting"],
			success : function(form, action) {
				
			}
		});
	}
	User.UpdateLoad();
	return form;
};
// Add Form
User.Form = function(frmId, url, params,title, id, role) {
	User.ResultStoreAdd = new Ext.data.JsonStore({
        root: 'listResult',
        idProperty: 'id',
        totalProperty: 'totalItems',
        fields: ['id', 'username', 'fullname' ,'email', 'address', 'active', { name: 'updateddate', type: 'date', dateFormat: 'c'}, 'updatedby'],
        proxy : new Ext.data.HttpProxy({url : url})
    });
User.Active = function(val){
	if(val == 0){
		return "<span style='color:red;font-weight:bold'>"+Resource["user.block"]+"</span>";
	}else if(val == 1){
		return "<span style='color:blue;font-weight:bold'>"+Resource["user.display"]+"</span>";
	}else{
		return val;
	}
}
User.GridResultAdd = new Ext.grid.GridPanel({
        store: User.ResultStoreAdd,
        trackMouseOver:true,
        disableSelection:false,
        loadMask: true,
        columns: [
        	new Ext.grid.RowNumberer()
        				,{header: Resource["user.fullname"], width: 100, sortable: true, dataIndex: 'fullname'}
        	        	,{header: Resource["user.username"], width: 100, sortable: true, dataIndex: 'username'}
        	        	,{header: Resource["user.active"], width: 100, sortable: true, dataIndex: 'active', renderer: User.Active}
        	        ],
        columnLines: true,
        stripeRows: true,
        autoWidth : true,
        height: 250,
        iconCls:'icon-grid',
        title: Resource["user.gridtitle"],
        viewConfig: {
            forceFit:true,
            enableRowBody:false,
            showPreview:false
        },
        
        bbar: new Ext.PagingToolbar({
            pageSize: 10,
            store: User.ResultStoreAdd,
            displayInfo: true,
            displayMsg: Resource["common.rangepage"],
            emptyMsg: Resource["common.emptypage"]
        }),
	    listeners : {
		    rowdblclick :{fn: function (grid, rowIndex, e) {
		    		var rows = grid.getSelectionModel().getSelections();
		    		if(role == 2){
			    		if (Ext.getCmp('maintabs-id').getItem('EditUser' + rows[0].data.id) != null) {
			    			Ext.getCmp('maintabs-id').getItem('EditUser' + rows[0].data.id).show();
			    		}else{
				    		var form = User.Form('EditUser' + rows[0].data.id, url, {'page' : 'edit', 'id' : rows[0].data.id}, title, rows[0].data.id, role );
				    		Ext.getCmp('maintabs-id').remove(frmId, true);
					    	Ext.getCmp('maintabs-id').add(form).show();
				    	}
		    		}
			    }}
		}
        
    });
	User.RoleDisplay = function(val){
		if(val != null && val != ''){
			if(val == 0){
				return '<span style="color:red;font-weight:bold;">'+Resource["user.role.notaccess"]+'</span>';
			}else if(val == 1){
				return '<span style="color:green;font-weight:bold;">'+Resource["user.role.readonly"]+'</span>';
			}else if(val == 2){
				return '<span style="color:blue;font-weight:bold;">'+Resource["user.role.canedit"]+'</span>';
			}
		}else{
			return '';
		}
	}
	User.storeDmRole = new Ext.data.SimpleStore({
		fields: ['id', 'name'],
		data: [['0', Resource["user.role.notaccess"]],['1', Resource["user.role.readonly"]], ['2',Resource["user.role.canedit"]]]
	});
	User.ComboRole = new Ext.form.ComboBox({
        store: User.storeDmRole,
        valueField: 'id',    
        displayField:'name',
        mode : 'local',
        typeAhead: true,
        forceSelection: true,
        triggerAction: 'all',
        emptyText: Resource["common.emptycombobox"],
        selectOnFocus:true,
        allowBlank: true,
        width:160
    });
	User.cm = new Ext.grid.ColumnModel({
        defaults: {
            sortable: true,
            forceFit:true,
            enableRowBody:false,
            showPreview:false
        },
        columns: [new Ext.grid.RowNumberer(),{
            header: Resource["user.menu.function"],
            dataIndex: 'menuname',
            width: 250
        },{
            header: Resource["user.menu.role"],
            dataIndex: 'role',
            width: 250,
            editor: User.ComboRole,
            renderer: User.RoleDisplay
        }]
    });
	User.storeRole = new Ext.data.JsonStore({
    	root: 'Menus',
        idProperty: 'menuid',
        remoteSort: false,
        fields: [
            'menuid','menuname','role'
        ]
    });
	User.RoleGrid = new Ext.grid.EditorGridPanel({
    	store: User.storeRole,
        cm: User.cm,
        anchor: '100%',
        autoWidth: true,
        height: 420,
        title: Resource["user.menufunction.gridtitle"],
        frame: true,
        iconCls:'icon-grid',
        clicksToEdit: 1
    });
	
	var hiddenPanel4Roles = new Ext.Panel({items: []});
	
	var form = new Ext.FormPanel({
    labelWidth: 120,
    closable:true,
    id : frmId,
    url:url,
    frame:true,
    title: title,
    bodyStyle:'padding:5px 5px 0',
    
    items: [{
    	layout: 'column',
    	items: [{
    		columnWidth: .5,
    		layout: 'form',
    		items:[{
	    	        xtype:'fieldset',
	    	        checkboxToggle:false,
	    	        title: title,
	    	        autoHeight:true,
	    	        defaults: {width: 250},
	    	        defaultType: 'textfield',
	    	        style: 'margin-right: 2px;',
	    	        collapsed: false,
	    	        items :[{
	    		                fieldLabel: Resource["user.fullname"],
	    		                name: 'fullname',
	    		                allowBlank:false
	    		            },{
	    		        		fieldLabel: Resource["user.username"],
	    		                name: 'username',
	    		                allowBlank:false
	    		            },{
	    		        		fieldLabel: Resource["user.password"],
	    		                name: 'password',
	    		                inputType : 'password',
	    		                allowBlank:false
	    		            },{
	    		                fieldLabel: Resource["user.email"],
	    		                name: 'email',
	    		                allowBlank : false,
	    		                vtype : 'email'
	    		            },{
	    		                xtype:'radiogroup',
	    		                id: 'activeId'+frmId,
	    						fieldLabel : Resource["user.active"],
	    						width : 200,
	    						allowBlank:true,
	    						items : [
	    						         {xtype : 'radio', boxLabel: Resource["user.display"], name: 'active', inputValue : 1, checked : true},
	    					             {xtype : 'radio', boxLabel: Resource["user.block"], name: 'active', inputValue : 0}
	    		               			]
	    		            },{
	    		                fieldLabel: Resource["user.address"],
	    		                name: 'address',
	    		                allowBlank : true
	    		            },{
	    		            	xtype : 'hidden',
	    		            	name : 'id'
	    		            },{
	    		            	xtype : 'hidden',
	    		            	name : 'crudaction',
	    		            	value : 'insert-update'
	    		            },{
	    		            	xtype : 'hidden',
	    		            	name : 'page',
	    		            	value : 'edit'
	    		            }
	    		        ]
	    	    },User.GridResultAdd
	        ]
    	},{
    		columnWidth: .5,
    		layout: 'form',
    		items:[{
	    	        xtype:'fieldset',
	    	        checkboxToggle:false,
	    	        title: Resource["user.menu.role"],
	    	        style: 'margin-left: 2px;',
	    	        autoHeight:true,
	    	        defaults: {width: 300},
	    	        defaultType: 'textfield',
	    	        collapsed: false,
	    	        items :[User.RoleGrid]
	    	    }
    		]
    	}]
    },hiddenPanel4Roles],

    tbar: new Ext.Toolbar([{
        text: Resource["common.btsave"],
        iconCls:'x-button-save',
        handler: function(){
	        if(form.getForm().isValid()){
	        	hiddenPanel4Roles.removeAll();
	        	var index = 0;
	        	var strParam = '';
	        	var arrParams = new Array();
	        	for (var i = 0; i <  User.storeRole.data.items.length; i++) {
        			if(User.storeRole.data.items[i].data.role != null && 
        					User.storeRole.data.items[i].data.role != '' && 
        					User.storeRole.data.items[i].data.menuid != '' && 
        					User.storeRole.data.items[i].data.menuid != null){
        				arrParams[index] = User.storeRole.data.items[i].data.menuid+'_'+User.storeRole.data.items[i].data.role;
		        		index ++;
        			}
	        	}
	        	strParam = arrParams.join('|');
	        	
	        	form.getForm().setValues([{id : 'crudaction', value : 'insert-update'}]);
	            form.getForm().submit({
	                url: url,
	                params: {'roles': strParam},
	                waitMsg: Resource["common.msgwaiting"],
	                success: function(userForm, o){
	            		if(o.result.messageResponse != null){
	            			Ext.MessageBox.show({
						           title: Resource["common.alert"],
						           msg: o.result.messageResponse,
						           buttons: Ext.MessageBox.OK
						       });
	            		}
	            		
	                    if (User.ListForm != null) {
	                    	User.GridResult.getStore().reload();
	                    }
	                    User.storeRole.loadData(o.result);
						User.ResultStoreAdd.loadData(o.result);
	                }
	            });
	        }
	    }
    },{
        text: Resource["common.btreset"],
        iconCls:'x-button-reset',
        handler: function(){
	    	if(form.getForm().findField('id').getValue() != ''){
	    		User.LoadEditForm();
	        }else{
	        	form.getForm().reset();
				form.getForm().setValues([{id : 'orderdisplay', value : '50'}]);
	        }
        }
    },{
        text: Resource["common.btback"],
        iconCls:'x-button-back',
        handler: function(){
        	if (Ext.getCmp('maintabs-id').getItem('User.ListForm') != null) {
        		Ext.getCmp('maintabs-id').getItem('User.ListForm').show();
        	}else{
            	Ext.getCmp('maintabs-id').add(User.ListForm('User.ListForm', url, {crudaction : 'search', pg4_offset : 0, maxPageItems : 10}, Resource["user.title"], role)).show();
            }
        }
    },{
        text: Resource["common.btclose"],
        iconCls:'x-button-close',
        handler: function(){
            Ext.getCmp('maintabs-id').remove(frmId, true);
        }
    }])
});
	User.LoadEditForm = function(val){
		form.getForm().load({
			url : url,
			params : params,
			waitMsg:Resource["common.msgwaiting"],
			success : function(form, action) {
			form.setValues([
							{id : 'id', value : action.result.data.id}
							,{id : 'active', value : action.result.data.active}
						]);
						if(action.result.data.active != null){
							Ext.getCmp('activeId'+frmId).setValue(action.result.data.active);
						}
						User.storeRole.loadData(action.result);
						User.ResultStoreAdd.loadData(action.result);
			}
		});
	}
	User.LoadEditForm();
	return form;
}

//List Form
User.ListForm = function(frmId, url, params, title, role) {
	User.ResultStore = new Ext.data.JsonStore({
        root: 'listResult',
        idProperty: 'id',
        totalProperty: 'totalItems',
        fields: ['id', 'username', 'fullname' ,'email', 'address', 'active', { name: 'updateddate', type: 'date', dateFormat: 'c'}, 'updatedby'],
        proxy : new Ext.data.HttpProxy({url : url})
    });
User.CheckAll = new Ext.grid.CheckboxSelectionModel();
User.Active = function(val){
	if(val == 0){
		return "<span style='color:red;font-weight:bold'>"+Resource["user.block"]+"</span>";
	}else if(val == 1){
		return "<span style='color:blue;font-weight:bold'>"+Resource["user.display"]+"</span>";
	}else{
		return val;
	}
}
User.GridResult = new Ext.grid.GridPanel({
        store: User.ResultStore,
        trackMouseOver:true,
        disableSelection:false,
        loadMask: true,
        columns: [
        	User.CheckAll,
        	new Ext.grid.RowNumberer()
        				,{header: Resource["user.fullname"], width: 100, sortable: true, dataIndex: 'fullname'}
        	        	,{header: Resource["user.username"], width: 100, sortable: true, dataIndex: 'username'}
        	        	,{header: Resource["user.email"], width: 100, sortable: true, dataIndex: 'email'}
        	        	,{header: Resource["user.address"], width: 100, sortable: true, dataIndex: 'address'}
        	        	,{header: Resource["user.active"], width: 100, sortable: true, dataIndex: 'active', renderer: User.Active}
        	        	,{header:  Resource["common.updateddate"], width: 100, sortable: true, dataIndex: 'updateddate', renderer : Ext.util.Format.dateRenderer('d/m/Y H:i:s')}
                      	,{header:  Resource["common.updatedby"], width: 100, sortable: true, dataIndex: 'updatedby'}
        	        ],
        sm : User.CheckAll,
        columnLines: true,
        stripeRows: true,
        autoWidth : true,
        autoHeight:true,
        iconCls:'icon-grid',
        title: title,
        viewConfig: {
            forceFit:true,
            enableRowBody:false,
            showPreview:false
        },
        bbar: new Ext.PagingToolbar({
            pageSize: 10,
            store: User.ResultStore,
            displayInfo: true,
            displayMsg: Resource["common.rangepage"],
            emptyMsg: Resource["common.emptypage"]
        }),
	    listeners : {
		    rowdblclick :{fn: function (grid, rowIndex, e) {
		    		var rows = grid.getSelectionModel().getSelections();
		    		if(role == 2){
			    		if (Ext.getCmp('maintabs-id').getItem('EditUser' + rows[0].data.id) != null) {
			    			Ext.getCmp('maintabs-id').getItem('EditUser' + rows[0].data.id).show();
			    		}else{
				    		var form = User.Form('EditUser' + rows[0].data.id, url, {'page' : 'edit', 'id' : rows[0].data.id},title+"-Sửa", rows[0].data.id, role);
					    	Ext.getCmp('maintabs-id').add(form).show();
				    	}
		    		}
			    }}
		}
        
    });
	

	var listForm = new Ext.FormPanel({
		closable:true,
		id : frmId,
	    url: url,
	    frame:true,
	    title: title,
	    bodyStyle:'padding:5px 5px 0',
		
	    items: [{
	    	id: frmId + 'searchfieldset',
	        xtype:'fieldset',
	        checkboxToggle:false,
	        title: Resource["common.searchinfo"],
	        autoHeight:true,
	        defaults: {width: 300},
	        defaultType: 'textfield',
	        collapsible : true,
	        items :[{
		                fieldLabel: Resource["user.fullname"],
		                name: 'fullname'
		            },{
		        		fieldLabel: Resource["user.username"],
		                name: 'username'
		            },{
		        		fieldLabel: Resource["user.email"],
		                name: 'email'
		            },{
		                xtype:'radiogroup',
						fieldLabel : Resource["user.active"],
						width : 300,
						allowBlank:true,
						items : [
								 {xtype : 'radio', boxLabel: Resource["user.all"], name: 'active',inputValue:'', checked :true},
						         {xtype : 'radio', boxLabel: Resource["user.display"], name: 'active', inputValue : 1},
					             {xtype : 'radio', boxLabel: Resource["user.block"], name: 'active', inputValue : 0}
		               			]
		            },{
		            	xtype : 'hidden',
		            	name : 'crudaction',
		            	value : 'search'
		            }]
	    }, User.GridResult],
	
	    tbar: new Ext.Toolbar([
	    	{
		        text: Resource["common.btnew"],
		        id: frmId+'btAdd',
	    		hidden: true,
		        iconCls:'x-button-add',
		        handler: function(){
		        	if (Ext.getCmp('maintabs-id').getItem('User') != null) {
		        		Ext.getCmp('maintabs-id').getItem('User').show();
		        	}else{
		        		Ext.getCmp('maintabs-id').add(User.Form('User', url, {'page': 'edit'}, title+'-Thêm', role)).show();
		        	}
		        }
		    },{
	        text: Resource["common.btdelete"],
	        id: frmId+'btDel',
	        hidden: true,
	        iconCls:'x-button-delete',
	        handler: function(){
		        var rows = User.CheckAll.getSelections();
	        	if (rows.length > 0) {
	        		Ext.Msg.show({
			       		title: Resource["common.alert"],
		   			 	msg: Resource["common.confirmdelete"],
		   			 	icon: Ext.MessageBox.QUESTION,
		   			 	buttons: Ext.MessageBox.OKCANCEL,
		   			 	fn: function(btn, text) {
		   			 		if(btn == 'ok') {
			   			 		listForm.getForm().setValues([{id : 'crudaction', value : 'delete'}]);
					        	queryStr = FormUtils.toQueryStr('checkList', rows);
					        	var urlDelete = url;
					        	if (queryStr != '') {
					        		urlDelete += '?' + queryStr;
					        	}
					            listForm.getForm().submit({
					                url: urlDelete,
					                waitMsg: Resource["common.msgwaiting"],
					                success: function(usergroupForm, o){
										User.ResultStore.loadData(o.result);
										if (o.result.messageRespone  != null && o.result.messageRespone != '') {
											Ext.MessageBox.show({
										           title: Resource["common.alert"],
										           msg: o.result.messageResponse,
										           buttons: Ext.MessageBox.OK
										       });
										}					                    
					                }
					           });
		   			 		}
	        			}
	        		})
		        }else{
		        		Ext.MessageBox.show({
					           title: Resource["common.alert"],
					           msg: Resource["common.mustselectonce"],
					           buttons: Ext.MessageBox.OK
					       });
		        }
	    	}
	        
	    },{
	        text: Resource["common.btsearch"],
	        iconCls:'x-button-search',
	        handler: function(){
		    	var searchfieldset = Ext.getCmp(frmId + 'searchfieldset');
		        if(searchfieldset.collapsed) {
		        	searchfieldset.expand(true);
		        	return;
		        }
		        if(listForm.getForm().isValid()){
		        	var rows = User.CheckAll.getSelections();
		        	var urlSearch = url;
		        	if(rows.length>0){
		        		queryStr = FormUtils.toQueryStr('checkList', rows);
			        	if (queryStr != '') {
			        		urlSearch += '?' + queryStr;
			        	}
		        	}
		           listForm.getForm().submit({
		                url: urlSearch,
		                waitMsg: Resource["common.msgwaiting"],
		                success: function(usergroupForm, o){
							User.ResultStore.loadData(o.result);
							if (o.result.messageRespone  != null && o.result.messageRespone != '') {
								Ext.MessageBox.show({
							           title: Resource["common.alert"],
							           msg: o.result.messageResponse,
							           buttons: Ext.MessageBox.OK
							       });
							}					                    
		                }
	            });
	        }
	    }
        
    },{
	        text: Resource["common.btreset"],
	        iconCls:'x-button-reset',
	        handler: function(){
	            listForm.getForm().reset();
	        }
	    },{
	        text: Resource["common.btclose"],
	        iconCls:'x-button-close',
	        handler: function(){
	        	Ext.getCmp('maintabs-id').remove(listForm);
	        }
	    }])
	});
	listForm.getForm().load({
		url : url,
		params : params,
		waitMsg: Resource["common.msgwaiting"],
		success : function(form, action) {
			User.ResultStore.loadData(action.result);
			if(role == 2){
				Ext.getCmp(frmId+'btAdd').show();
				Ext.getCmp(frmId+'btDel').show();
			}
		},
		failure : function(form, action) {
		}
	});
	return listForm;
};